package com.jflyfox.modules.admin.course;

import com.jfinal.plugin.activerecord.Page;
import com.jflyfox.component.base.BaseProjectController;
import com.jflyfox.jfinal.base.BaseModel;
import com.jflyfox.jfinal.component.annotation.ControllerBind;
import com.jflyfox.jfinal.component.db.SQLUtils;
import com.jflyfox.util.StrUtils;

@ControllerBind(controllerKey = "/admin/course")
public class CourseController extends BaseProjectController {
    private static final String path = "/pages/admin/course/course_";

    public void index(){
       renderMessage("hhh");
    }
    public void list() {
        TbCourse model = getModelByAttr(TbCourse.class);

        // 这里是拼接查询sql并且获取前台传递的参数
        SQLUtils sql = new SQLUtils(" from tb_course t where 1=1 ");
        if (BaseModel.getAttrValues(model).length != 0) {
            sql.setAlias("t");
            sql.whereLike("course", model.getStr("course"));
            sql.whereEquals("type", model.getStr("type"));
        }

        // 这里是统一做了排序功能
        String orderBy = getBaseForm().getOrderBy();
        if (StrUtils.isEmpty(orderBy)) {
            sql.append(" order by id desc ");
        } else {
            sql.append(" order by ").append(orderBy);
        }

        Page<TbCourse> page = TbCourse.dao.paginate(getPaginator(), "select t.* ", //
                sql.toString().toString());

        // 下拉框
        setAttr("page", page);
        setAttr("attr", model);
        render(path + "list.html");
    }

    public void add() {
        render(path + "add.html");
    }

    public void view() {
        TbCourse model = TbCourse.dao.findById(getParaToInt());
        setAttr("model", model);
        render(path + "view.html");
    }

    public void delete() {
        TbCourse model = new TbCourse();
        Integer userid= getSessionUser().getUserid();
        String now = getNow();
        model.put("update_id", userid);
        model.put("update_time", now);
        model.deleteById(getParaToInt());

        list();
    }

    public void edit() {
        TbCourse model = TbCourse.dao.findById(getParaToInt());
        setAttr("model", model);
        render(path + "edit.html");
    }

    public void save() {
        Integer pid = getParaToInt();
        TbCourse model = getModel(TbCourse.class);


        Integer userid= getSessionUser().getUserid();
        String now = getNow();
        // 这两个字段设置为了日志收集
        model.put("update_id", userid);
        model.put("update_time", now);
        if (pid != null && pid > 0) { // 更新
            model.update();
        } else { // 新增
            model.remove("id");
            model.put("create_id", userid);
            model.put("create_time", now);
            model.save();
        }
        renderMessage("保存成功");
    }
}

